import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * Author :  Rocky
 * Date : 24/05/2017 23:13
 * Description :
 * Test :
 */
public class SingleThreadSingleFileTest {
    public static void main(String[] args) throws IOException {
        long s = System.currentTimeMillis();


        for (int i = 0; i < 10; i++) {

            Random random = new Random();
            List<MappedByteBuffer> mbbList = new ArrayList<>();

            for (int j = 0; j < 20; j++) {
                File file = new File("testfile" + j);
//            file.deleteOnExit();
                if (file.exists()) {
                    file.exists();
                }
                RandomAccessFile raf = new RandomAccessFile(file, "rw");
                MappedByteBuffer mbb = raf.getChannel().map(FileChannel.MapMode.READ_WRITE, 0, 100 * 1024 * 1024);
                mbbList.add(mbb);
            }

            byte data = 4;
            int byteCount = 30 * 1024 * 1024 / 4;
            while (mbbList.size() > 0) {
                MappedByteBuffer mbb = mbbList.get(random.nextInt(mbbList.size()));

                int k = 0;
                while (k++ <= byteCount && mbb.hasRemaining()) {
                    mbb.put(data);
                }


                if (!mbb.hasRemaining()) {
                    mbbList.remove(mbb);
                }
            }
        }
        long time = (System.currentTimeMillis() - s);
        long totalBytes = 20000; //单位m
        System.out.println("1个线程1个文件，文件大小2000m，循环10次， 总耗时 " + time + " ms ，速度 " + (totalBytes * 1024 / (time * 1.0 / 1000)) + " kb/s");
    }
}
